#include "custom_image_canvas.hpp"
#include <iostream>
#include <QPainter>
// #include <QFont>
// #include <QPen>

CustomImageCanvas::CustomImageCanvas()
{
  std::cout << "create CustomImageCanvas" << std::endl;
  this->setFixedSize(800, 600);
}

void CustomImageCanvas::paintEvent(QPaintEvent *event)
{
  QPainter painter(this);
  painter.setRenderHint(QPainter::Antialiasing, true); // 抗锯齿
  painter.setPen(QColor(0, 0, 255));                   // 画笔颜色
  int cw = this->rect().width();
  int ch = this->rect().height();
  // 使用QPainter对象的fillRect函数来绘制一个矩形，并填充为透明色
  painter.fillRect(this->rect(), QColor(0, 0, 0));

  if (!this->pix_map_.isNull())
  {
    auto temp = pix_map_.scaled(QSize(800, 600), Qt::KeepAspectRatio);
    int iw = temp.width();
    int ih = temp.height();
    int shift_x = (cw - iw) / 2;
    int shift_y = (ch - ih) / 2;
    painter.drawImage(QRectF(shift_x, shift_y, iw, ih), temp.toImage());
  }
  QFont Font;
  Font.setPixelSize(36);
  painter.setFont(Font);
  painter.drawText(QPoint(100, 100), text_info_);

  // 绘制跟填充不同的几何形状
  QPen pen(Qt::green);
  pen.setWidth(4);
  pen.setStyle(Qt::DashLine); 
  // pen.setStyle(Qt::DotLine);
  // pen.setStyle(Qt::DashDotLine);
  // pen.setStyle(Qt::DashDotDotLine);
  // pen.setStyle(Qt::CustomDashLine);
  // pen.setStyle(Qt::NoPen);
  // pen.setStyle(Qt::SolidLine);


  painter.setPen(pen);
  painter.drawRect(QRectF(300, 200, 300 ,300));

  pen.setColor(Qt::red);
  pen.setStyle(Qt::NoPen);
  // painter.setPen(pen);
  QBrush brush(Qt::yellow);
  painter.setBrush(brush);
  painter.drawEllipse(QPoint(200, 200), 200, 100);

  pen.setColor(Qt::blue);
  pen.setStyle(Qt::DashDotLine);
  painter.setPen(pen);
  painter.drawLine(QPoint(300, 200), QPoint(600, 500));

  QPolygon pts;
  pts.append(QPoint(100, 100));
  pts.append(QPoint(100, 200));
  pts.append(QPoint(200, 250));
  pts.append(QPoint(250, 350));
  pts.append(QPoint(300, 100));
  brush.setColor(Qt::red);
  // brush.setStyle(Qt::Dense1Pattern);
  brush.setStyle(Qt::CrossPattern);
  painter.setBrush(brush);
  pen.setColor(Qt::red);
  painter.setPen(pen);
  painter.drawPolygon(pts);
}

void CustomImageCanvas::setTextInfo(const QString &text)
{
  text_info_ = text;
  this->repaint();
}

void CustomImageCanvas::setImage(const QPixmap &image)
{
  if (image.isNull())
  {
    std::cout << "Attempted to set null image\n";
    return;
  }
  pix_map_ = image;
  this->repaint();
}
